#ifndef GAMECLIENT_H
#define GAMECLIENT_H

#include <QObject>
#include <QTcpSocket>
#include <QHostAddress>
#include <QJsonObject>
#include <QList>

#include "card.h"
#include "message.h"
#include "gamestate.h"
#include "garbagebin.h"

class GameWindow;

class GameClient : public QObject
{
    Q_OBJECT
public:
    GameClient();
    ~GameClient();

    static constexpr int numPlayers = 3;
    static constexpr int maximumCards = 20;

    bool connectToServer(const QHostAddress& serverAddress, quint16 serverPort);
    void stop();

    friend class GameWindow;

signals:
    void clientStopping(const QString& why);
    void startGame();
    void clientStateChanged();
    void clientUpdated();
    void cardsPosted(bool success);

private slots:
    void onReadyRead();
    void onServerDisconnected();

private:
    void action(Message& m, const QByteArray& s);
    void unpackMessage(const QByteArray& s);
    void doPreempt(bool);
    void postCards(bool skip);
    void restartGame();
    void resetState();
    bool judgeWinner(int id = -1);

    QTcpSocket *socket;

    GarbageBin<QTcpSocket> garbage;

    GameState state;
    QJsonObject go;
    bool selected[maximumCards]; // handcards selected
    bool dataReady, mustPost, postIllegal;
    int winner;
    QList<Card> handCards;
};

#endif // GAMECLIENT_H
